// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { js, UITransform, v3 } from "cc";
import { GRoot, UIPackage } from "fairygui-cc";
import { FuiCom } from "../../ui_gen/FuiCom";
import { Ctor, RFCtrl } from "../puremvc/RegistFunc";
import { Defer } from "../Utils/Defer";
import { GameFacade } from "../puremvc/GameFacade";

const ViewCycle = 600;//10分钟检测一次资源释放
export class UI {
    static loadedPkg: Map<string, UIPackage> = new Map();
    static comInfoMap: Map<Ctor<any>, { pkgName: string, comName: string }> = new Map();
    public static registFui<T extends FuiCom>(ctor: Ctor<T>, pkgName: string, comName: string) {
        if (pkgName == "Common") {
            RFCtrl(GameFacade)(ctor);
        }
        else {
            // let facade = js.getClassByName(pkgName + "Facade") as Ctor<BaseFacade>;
            let facade = GameFacade;
            if (!facade) {
                console.error("没有找到fui包对应的Facade，请保证包名为Facade前缀：", pkgName);
            }
            RFCtrl(facade)(ctor);
        }
        this.comInfoMap.set(ctor, { pkgName, comName });
    }
    public static init() {
        GRoot.create();
        GRoot.inst.visible = true;
        GRoot.inst.node.getComponent(UITransform).anchorX = GRoot.inst.node.getComponent(UITransform).anchorY = 0.5;
        GRoot.inst.node.position = v3();
    }
    static async loadFuiPkg(pkgName: string) {
        if (this.loadedPkg.has(pkgName)) return;
        js.getClassByName(pkgName + "Binder")['bindAll']?.();
        let defer = new Defer();
        UIPackage.loadPackage(pkgName, (err, pkg) => {
            if (err) {
                console.error(err);
                defer.reject();
            }
            else {
                this.loadedPkg.set(pkgName, pkg);
                defer.resolve();
            }
        })
        await defer.promise;
    }
    static unLoadFuiPkg(pkgName: string) {
        this.loadedPkg.delete(pkgName);
    }
    static isLoadPkg(pkgName: string) {
        return this.loadedPkg.has(pkgName);
    }
}
window['UI'] = UI;
